package com.example.wu5hen.n0te;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.content.res.Resources;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;

import com.example.wu5hen.n0te.Fields.DiaryColumns;

import java.util.Calendar;

public class DiaryProvider extends ContentProvider{
    //日记本中变量
    private static final String DATABASE_NAME="database";
    private static final int DATABASE_VERSION=1;
    private static final String DIARY_TABLE_NAME="diary";
    private static final int DIARIES=1;
    private static final int DIARY_ID=2;
    //定义UriMatcher 匹配URI类型
    private static final UriMatcher sUriMatcher;
    static {
        sUriMatcher=new UriMatcher(UriMatcher.NO_MATCH);
        sUriMatcher.addURI(Fields.AUTHORITY,"diaries",DIARIES);
        sUriMatcher.addURI(Fields.AUTHORITY,"diaries/#",DIARY_ID);
    }

    private DatabaseHelper mOpenHelper;
    private static class DatabaseHelper extends SQLiteOpenHelper {
        DatabaseHelper(Context context) {
            super(context, DATABASE_NAME, null, DATABASE_VERSION);
            Log.i("wus", "DATABASE_VERSION=" + DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            Log.i("wus", "onCreate(SQLiteDatabase db)");
            String sql;
            sql = "CREATE TABLE " + DIARY_TABLE_NAME + " ("
                    + DiaryColumns._ID + " INTEGER PRIMARY KEY,"
                    + DiaryColumns.TITLE + " varchar(255)," + DiaryColumns.BODY
                    + " TEXT," + DiaryColumns.CREATED + " TEXT" + ");";

            Log.i("wus", "sql=" + sql);
            db.execSQL(sql);
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            Log.i("wus",
                    " onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)="
                            + newVersion);
            db.execSQL("DROP TABLE IF EXISTS diary");
            onCreate(db);
        }
    }
    //获取当前时间的函数
    public static  String getFormateCreatedDate(){
        Calendar calendar=Calendar.getInstance();
        String created=calendar.get(Calendar.YEAR)+"年"
                +(calendar.get(Calendar.MONTH)+1)+"月"
                +calendar.get(Calendar.DAY_OF_MONTH)+"日"
                +calendar.get(Calendar.HOUR_OF_DAY)+"时"
                +calendar.get(Calendar.MINUTE)+"分";
        return created;
    }
    @Override
    public boolean onCreate(){
        mOpenHelper=new DatabaseHelper(getContext());
        return true;
    }
    @NonNull
    @Override
    public Cursor query(Uri uri,String[] projection,String selection,
                        String[] selectionArgs,String sortOrder){
        SQLiteQueryBuilder qb=new SQLiteQueryBuilder();

        switch (sUriMatcher.match(uri)) {
            case DIARIES:
                qb.setTables(DIARY_TABLE_NAME);
                break;
            case DIARY_ID:
                qb.setTables(DIARY_TABLE_NAME);
                qb.appendWhere(DiaryColumns._ID + "="
                        + uri.getPathSegments().get(1));
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }
        String orderBy;
        if(TextUtils.isEmpty(sortOrder)){
            orderBy= DiaryColumns.DEFAULT_SORT_ORDER;
        }
        else{
            orderBy=sortOrder;
        }
        SQLiteDatabase db=mOpenHelper.getReadableDatabase();
        Cursor c=qb.query(db,projection,selection,selectionArgs,
                null,null,orderBy);
        return c;
    }
    public String getType(Uri uri){
        switch (sUriMatcher.match(uri)){
            case DIARIES:
                return DiaryColumns.CONTENT_TYPE;
            case DIARY_ID:
                return DiaryColumns.CONTENT_ITEM_TYPE;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }
    }
    @NonNull
    @Override
    public Uri insert(Uri uri,ContentValues initialValues){
        if(sUriMatcher.match(uri)!=DIARIES){
            throw new IllegalArgumentException("Unknown URI " + uri);
        }
        ContentValues values;
        if(initialValues!=null){
            values=new ContentValues(initialValues);
        }
        else{
            values=new ContentValues();
        }
        if(!values.containsKey(DiaryColumns.CREATED))
            values.put(DiaryColumns.CREATED,getFormateCreatedDate());
        if(!values.containsKey(DiaryColumns.TITLE)){
            Resources r=Resources.getSystem();
            values.put(DiaryColumns.TITLE,r.getString(android.R.string.untitled));
        }
        if (!values.containsKey(DiaryColumns.BODY)) {
            values.put(DiaryColumns.BODY, "");
        }
        SQLiteDatabase db=mOpenHelper.getWritableDatabase();
        //插入一条记录到数据库当中
        long rowId=db.insert(DIARY_TABLE_NAME, DiaryColumns.BODY,values);
        Log.e("rowID=", "====="+rowId);
        if(rowId>0){
            Log.e("in and out???", "ggggggg " );
            return ContentUris.withAppendedId(DiaryColumns.CONTENT_URI,rowId);
        }
        //throw new SQLException("Failed to insert row into " + uri);
        return null;
    }
    @NonNull
    @Override
    public int delete(Uri uri,String where,String[] whereArgs){
        //getWritableDatabase（）方法得到一个string的list
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        //得到rowId的值，如果get（0）那值就为diaries
        String rowId = uri.getPathSegments().get(1);
        //标准的SQLite删除操作，第一个参数是数据表的名字
        //第二个相当于SQL语句中的where部分。
        return db.delete(DIARY_TABLE_NAME, DiaryColumns._ID +
                "=" + rowId, null);
    }
    @NonNull
    @Override
    public int update(Uri uri, ContentValues values, String where,
                      String[] whereArgs) {
        //getWritableDatabase（）方法得到SQLiteDatabase的实例
        SQLiteDatabase db = mOpenHelper.getWritableDatabase();
        //得到rowId的值
        String rowId = uri.getPathSegments().get(1);
        //最后在调用update语句执行更新操作
        return db.update(DIARY_TABLE_NAME, values, DiaryColumns._ID +
                "="+ rowId, null);
    }
}
